#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

typedef struct 
{
	int id ; 
	char name[20] ;
	double sal;
}Employee;

int main()
{
	//1. create a file
	int fd = open("emp.dat" , O_CREAT | O_RDWR | O_TRUNC , 0666);
	if(fd == -1) perror("open") , exit(-1);
	
	//2. expand file space; , this's the most important step!!!
	ftruncate(fd , sizeof(Employee)*3);

	//3. apply for space , if flag == MAP_PRIVATE , then other processes can't see contents.
	void * p = mmap( 0 , sizeof(Employee)*3 , PROT_WRITE | PROT_READ , MAP_SHARED , fd , 0 );
	if(p == MAP_FAILED) perror("mmap") , exit(-1);
	
	//4. create a structure pointer which point to the p ;
	Employee *emp = p;
	emp[0].id = 1 ;
	strcpy(emp[0].name , "ali");
	emp[0].sal = 1022.3;
	
	emp[1].id = 2 ;
	strcpy(emp[1].name , "cristiano");
	emp[1].sal = 1023.8;
	
	emp[2].id = 3 ;
	strcpy(emp[2].name , "kaka");
	emp[2].sal = 1024.5;
	//5. release the space of p	
	munmap(p , sizeof(Employee)*3);
}
